// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
const col = db.collection('test02');
const _= db.command;

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()

    //查询数据
    let user = await col.where({
        '_openid':wxContext.OPENID
    }).get();
    user = user.data[0];
    //记得修改呀呀呀有~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if(user.prize !== null){
        return{
            msg:'你已经抽过奖了！！！ ',
            success:false
        }
    }

    let rand = Math.random();
    let prize;
    switch(true){
        case(rand < 0.1):
        prize = 1;
        break;
        case(rand >= 0.1 && rand < 0.4):
        prize = 2;
        break;
        case(rand >= 0.4):
        prize = 0;
        break;
    }

    //选中的油卡数量减一
    let zero = event.selectedArr[0];
    let one = event.selectedArr[1];
    user.words[zero].number -=1;
    user.words[one].number -=1;

    await col.where({
        '_openid':wxContext.OPENID
    }).update({
        data:{
            prize:prize,
            words:user.words
        }
    })
    return {
        prize:prize,
        success:true,
        words:user.words
    }
}